﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace PolePosition.v3.Desktop
{
    public partial class FormLogin : DevComponents.DotNetBar.Office2007Form
    {
        public FormLogin()
        {
            InitializeComponent();

            labelXCopyright.Text = string.Format(labelXCopyright.Text,
                DateTime.Today.Year, Program.VersionNumber, Program.BuildNumber);

            m_WorkingColor = labelXWaitText.ForeColor;
            m_ErrorColor = Color.Red;


            //todo: remove
            if (Environment.MachineName.ToLower() == "ppidev-wes"
                || Environment.MachineName.ToLower() == "jerry-vpc3"
                || Environment.MachineName.ToLower() == "pc12")
            {
                txtUsername.Text = "ppi";
                txtPassword.Text = "Passw0rd";
                btnLogin_Click(btnLogin, EventArgs.Empty);
            }
        }

        private readonly Color m_WorkingColor;
        private readonly Color m_ErrorColor;
        private string m_UserName;
        private string m_Password;

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (m_LoginAttempts > 10)
            {
                txtUsername.Enabled = false;
                txtPassword.Enabled = false;
                btnLogin.Enabled = false;
                ShowErrorText("Too many failed login attempts.");
                return;
            }

            if (backgroundWorkerLogin.IsBusy)
                return;

            if (string.IsNullOrEmpty(txtUsername.Text.Trim()))
            {
                txtUsername.Border.BorderColor = Color.Red;
                txtUsername.Focus();
                ShowErrorText("User Name is Required");
                return;
            }
            txtUsername.Border.BorderColor = Color.Black;


            if (string.IsNullOrEmpty(txtPassword.Text.Trim()))
            {
                ShowErrorText("Password is Required");
                txtPassword.Border.BorderColor = Color.Red;
                txtPassword.Focus();
                return;
            }
            txtPassword.Border.BorderColor = Color.Black;
            
            m_UserName = txtUsername.Text.Trim();
            m_Password = txtPassword.Text.Trim();

            m_LoginAttempts++;
            ShowProcessingText("Attempting Login. Please wait.");

            //start the asynch process
            backgroundWorkerLogin.RunWorkerAsync();
        }

        int m_LoginAttempts;

        private void backgroundWorkerLogin_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = ServiceProxy.AdministrationService.DoLogin(m_UserName, m_Password);

            if ((sender as BackgroundWorker).CancellationPending)
                e.Cancel = true;
        }

        private void backgroundWorkerLogin_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;

            if (e.Error != null || e.Result == null)
            {
                //handle error 
                ShowErrorText("Login failed. Please try again.");
                return;
            }

            EntityLibrary.LoginEntity _LoginResult = e.Result as EntityLibrary.LoginEntity;

            if (_LoginResult == null)
            {
                //handle error 
                ShowErrorText("Login failed. Please try again.");
                return;
            }


            if (!_LoginResult.Success)
            { 
                ShowErrorText("Unknown user name or password");
                return;
            }

            bool _Enabled;
            switch (_LoginResult.LoginUserType)
            {
                case EntityLibrary.LoginEntity.LoginUserTypes.Vendor:
                    _Enabled = _LoginResult.VendorContact.Enabled.Value;
                    break;
                case EntityLibrary.LoginEntity.LoginUserTypes.Utility:
                    _Enabled = _LoginResult.UtilityContact.Enabled.Value;
                    break;
                case EntityLibrary.LoginEntity.LoginUserTypes.PPI:
                    _Enabled = true;
                    break;
                default:
                    ShowErrorText("Unknown login type");
                    return;
            }

            if (!_Enabled)
            {
                //handle not enabled 
                ShowErrorText("Unable to login. Please contact your PPI sales representative.");
                return;
            }

            Program.LoginResult = _LoginResult;
            DialogResult = DialogResult.OK;
        }

        private void ShowProcessingText(string text)
        {
            labelXWaitText.ForeColor = m_WorkingColor;
            labelXWaitText.Text = text; 
            progressBarXWait.Visible = true;
            labelXWaitText.Visible = true;
        }

        private void ShowErrorText(string text)
        {
            labelXWaitText.ForeColor = m_ErrorColor;
            labelXWaitText.Text = text;
            progressBarXWait.Visible = false;
            labelXWaitText.Visible = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (backgroundWorkerLogin.IsBusy)
                backgroundWorkerLogin.CancelAsync();
        }

        private void txtPassword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                btnLogin_Click(btnLogin, EventArgs.Empty);
            }
        }
    }
}
